/**
 * Created by hzc
 */

/**2个异步获取数据线程任务计数器,减到0表示任务结果获取完成!;*/
var LOAD_DATA_COUNT = 0;
var submitFn = true;//防止重复提交
var smConsumeConstants = {"voucherIndex":""};
(function(doc, win) {

    //var soucherCHangeFlag = false;//是否需要重新获取活动预期效果

    // sui 页面就绪时间
    $(doc).on("pageInit", "#smCreateConsumePage", function(e, pageId, $page,isBack) {
        
        var controller = new ActivityCreateConsumeSmController();
        ActivityPreloadData.loadDataTimer({
            "func0" : function() {
                ActivityPreloadData.createPrerequisite();
            },
            "callBackEvent" : function() {
                if(isBack){
                    // 其他设置页返回，需要保存其他设置页的参数信息
                    var paramObj = CommonUtil.takeOutParamObject();
                    $.extend(createActivityPublicParam.otherSetting,paramObj);

                    //绑定活动日期联动控件;
                    controller.bindVoucherTimeWidget();   
                    return;
                }else{
                    // 从首页点击来,保存默认券信息
                    var defaultParam = CommonUtil.takeOutParamObject();

                    defaultParam.activityStartTime = DateUtil.getDateFormat(new Date());
                    defaultParam.activityEndTime = DateUtil.getDateFormat(DateUtil.addDays(new Date(),defaultParam.activityValidDays.split("|")[0]));
             
                    createActivityPublicParam.activityType = defaultParam.activityType;
                    createActivityPublicParam.activityStartTime = defaultParam.activityStartTime;
                    createActivityPublicParam.activityEndTime = defaultParam.activityEndTime;



                    var voucherRelativeTime = defaultParam.voucherRelativeTime.split("|")[0]==''?'30': defaultParam.voucherRelativeTime.split("|")[0];
                    createActivityPublicParam.voucherStartTime = DateUtil.getDateFormat(new Date());
                    createActivityPublicParam.voucherEndTime = DateUtil.getDateFormat(DateUtil.addDays(new Date(),voucherRelativeTime));
       
                    $.extend(createActivityPublicParam.defaultParam,defaultParam);
                    
                    //生成默认其他页面参数        
                    generateDefaultOtherSetting();
                    controller.redrawFirstStepView(createActivityPublicParam.defaultParam);

                    //绑定活动日期联动控件;
                    controller.bindVoucherTimeWidget();   
                }
            }
        });

    });

    //券删除
    $(doc).on("click", "#smCreateConsumePage .quan .remove", function() {
        var index = $(this).attr("voucherIndex");

        var promoTools = createActivityPublicParam.otherSetting.promoTools;
        promoTools.splice(index,1);

        var controller = new ActivityCreateConsumeSmController();
        controller.redrawFirstStepView();
    });

        
    //其他页面跳转
    $(doc).on("click", "#smCreateConsumePage .link-to-otherSetting", function() {
        jumpOtherSettingPage();

    });

    
    /**
        券设置弹窗
    **/
    //添加优惠券
    $(doc).on("click", "#smCreateConsumePage .btn-add-quan", function() {
        if($("#smCreateConsumePage .btn-add-quan").hasClass("disabled")){
            return;
        }

        showVoucherView();

        $("#smCreateConsumePage .form-title").text("添加优惠券");
        //领取条件：订单满XX元    
        $("#smCreateConsumePage .dailog-form .promoSendRuleMincost").val("");
        //券面额
        $("#smCreateConsumePage .dailog-form .voucherWorthValue").val("");
        //券消费门槛
        $("#smCreateConsumePage .dailog-form .voucherMinConsume").val("");
        
        //确认按钮高亮可用
        $("#smCreateConsumePage .dailog-form .sure").addClass("disabled");

    });

    //编辑优惠券
    $(doc).on("click", "#smCreateConsumePage .quan", function() {

        showVoucherView();
        var voucherDataArray = createActivityPublicParam.otherSetting.promoTools;

        smConsumeConstants.voucherIndex = $(this).attr("id");
        var voucherData = voucherDataArray[smConsumeConstants.voucherIndex];


        log4JS.info("领取条件1="+JSON.stringify(voucherData));
        $("#smCreateConsumePage .form-title").text("设置优惠券");

        //领取条件：订单满XX元    
        $("#smCreateConsumePage #promoSendRuleMincost").val(voucherData.promoSendRuleMincost);
        //券面额
        $("#smCreateConsumePage #voucherWorthValue").val(voucherData.voucherWorthValue);
        //券消费门槛
        $("#smCreateConsumePage #voucherMinConsume").val(voucherData.voucherMinConsume);
        
        //确认按钮高亮可用
        $("#smCreateConsumePage .dailog-form .sure").removeClass("disabled");
        log4JS.info("领取条件="+$("#smCreateConsumePage #promoSendRuleMincost").val());

    });

    $(doc).on("click", "#smCreateConsumePage .dailog-form .cancel,.dailog-form .layer-overlay", function() {
        closeVoucherView();
    });

    //显示弹窗
    function showVoucherView(){
        closeVoucherView();
        //券设置弹窗
        var df = $("#smCreateConsumePage .dailog-form");
        log4JS.info("+打开弹窗"+df.attr("class"));
        df.addClass("layer-visible");    
        log4JS.info("+弹窗class"+df.attr("class"));
    }   

    //关闭弹窗-公用
    function closeVoucherView(){
        //券设置弹窗
        var df = $("#smCreateConsumePage .dailog-form ");
        log4JS.info("-关闭弹窗"+df.attr("class"));
        df.removeClass("layer-visible");
        log4JS.info("-弹窗class"+df.attr("class"));
    }

    //券设置弹窗确认按钮状态控制
    $(doc).on("input", "#smCreateConsumePage .dailog-form input", function(e) {
        var reg = new RegExp("^[0-9]+\.{0,1}[0-9]{0,2}$");   
        var inputVal = $(this).val();
        if(inputVal == ""){
            $(this).val("");
        }else{
            if(!reg.test(inputVal)){
                var indexOfPoint =inputVal.indexOf(".");
                if(indexOfPoint != -1){
                    if(inputVal.substring(indexOfPoint+1).length>2){
                        $(this).val(inputVal.substring(0,indexOfPoint+3));
                    }
                } 
            }else{
                if(inputVal.charAt(0)=='0'&& inputVal.charAt(1)!='' && inputVal.charAt(1)!='.'){
                    $(this).val(Number(inputVal));
                }
            }
            
        }
        //领取条件：订单满XX元    
        var promoSendRuleMincost = $("#smCreateConsumePage .dailog-form .promoSendRuleMincost").val();
        //券面额
        var voucherWorthValue = $("#smCreateConsumePage .dailog-form .voucherWorthValue").val();
        //券消费门槛
        var voucherMinConsume = $("#smCreateConsumePage .dailog-form .voucherMinConsume").val();
        
       //var voucherLogo = $("#smCreateConsumePage .dailog-form .voucherLogo").val();
        if(CommonUtil.isEmpty(promoSendRuleMincost)||CommonUtil.isEmpty(voucherWorthValue)
            ||CommonUtil.isEmpty(voucherMinConsume)){
            //信息不全,按钮置灰不可用
            $("#smCreateConsumePage .dailog-form .sure").addClass("disabled");
        }else{        

            //确认按钮高亮可用
            $("#smCreateConsumePage .dailog-form .sure").removeClass("disabled");
        }

    });

    //券设置-确认
    $(doc).on("click", "#smCreateConsumePage .dailog-form .sure", function() {
        if($("#smCreateConsumePage .dailog-form .sure").hasClass("disabled")){
            return;
        }

        //领取条件：订单满XX元    
        var promoSendRuleMincost = $("#smCreateConsumePage .dailog-form .promoSendRuleMincost").val();
        //券面额
        var voucherWorthValue = $("#smCreateConsumePage .dailog-form .voucherWorthValue").val();
        //券消费门槛
        var voucherMinConsume = $("#smCreateConsumePage .dailog-form .voucherMinConsume").val();
        // if(parseFloat(voucherWorthValue)<parseFloat(voucherMinConsume)*0.05){
        //     DialogUtil.dialogWarn("为了吸引更多的顾客到店消费,建议券面额不低于订单价的5%");
        //     return;
        //  }

        if (!(/^\+?(0|[1-9][0-9]*)$/.test(promoSendRuleMincost))) {
            DialogUtil.dialogWarn('领取条件仅允许输入整数');
            return false;
        }
 
        if (promoSendRuleMincost < 0 || promoSendRuleMincost > 50000) {
            DialogUtil.dialogWarn("领取条件金额必须输入大于等于0且小于等于50000的数字!");
            return false;
        }

        if(isNaN(voucherWorthValue)){
            DialogUtil.dialogWarn('券面额仅允许输入数字');
            return false;
        }
        if (voucherWorthValue <= 0 || voucherWorthValue > 999.99) {
            DialogUtil.dialogWarn("券面额必须输入大于0且小于999.99的数字!");
            return false;
        }

        if(isNaN(voucherMinConsume)){
            DialogUtil.dialogWarn('券消费门槛金额仅允许输入数字');
            return false;
        }
        if (voucherMinConsume < 0 || voucherMinConsume > 9999.99) {
            DialogUtil.dialogWarn("券消费门槛金额必须输入大于等于0且小于9999.99的数字!");
            return false;
        }


        var voucher = {};
        voucher.promoSendRuleMincost = promoSendRuleMincost;
        voucher.voucherWorthValue = parseFloat(voucherWorthValue).toFixed(2);
        voucher.voucherMinConsume = voucherMinConsume;
        voucher.voucherName = buildVourcherName($("#smCreateConsumePage .dailog-form .voucherWorthValue").val());

        //补充券的默认参数
        var defaultParam = createActivityPublicParam.defaultParam;
        voucher.voucherRelativeTime = createActivityPublicParam.voucherRelativeTime;
        voucher.voucherType = defaultParam.voucherType;
        voucher.crowdGroup = defaultParam.crowdGroup;


        //更新券信息到otherSetting
         var otherSetting = createActivityPublicParam.otherSetting;
        var isAddQuan = ($("#smCreateConsumePage .form-title").text().indexOf("添加")!=-1)?true:false; 
         if(isAddQuan==true){
            //将新元素添加到数组开始，数组中的元素自动后移，返回数组新长度
            otherSetting.promoTools.unshift(voucher);
         }else{
             $.extend(otherSetting.promoTools[smConsumeConstants.voucherIndex],voucher);
         }

        //重新渲染券页面
        var controller = new ActivityCreateConsumeSmController();
        controller.redrawFirstStepView();
        $("#smCreateConsumePage .dailog-form .sure").addClass("disabled");
        closeVoucherView();
    });


    //下一步按钮
    $(doc).on("click", "#smCreateConsumePage .nextStep", function() {

        if($("#smCreateConsumePage .nextStep").hasClass("disabled")){
            return;
        }
        var controller = new ActivityCreateConsumeSmController();

        /**
        *  将券有效期赋值给券
        **/
        var voucherValidateType = createActivityPublicParam.isRelativeTime?"RELATIVE":"FIXED";
        var voucherStartTime = createActivityPublicParam.voucherStartTime;
        var voucherEndTime = createActivityPublicParam.voucherEndTime;

        var otherSetting = createActivityPublicParam.otherSetting;
        var voucherRelativeTime  = $("#smCreateConsumePage #voucherRelativeTime").val();


        if (voucherRelativeTime <= 0 || voucherRelativeTime == "") {
            DialogUtil.dialogWarn("券有效期相对时间最小为1天");
            return false;
        }
        if(voucherRelativeTime>365){
            DialogUtil.dialogWarn("券有效期相对时间不能大于365天!");
            return false;
        }
        if (!(/^\+?(0|[1-9][0-9]*)$/.test(voucherRelativeTime))) {
            DialogUtil.dialogWarn('券有效期相对时间仅允许输入整天数');
            return false;
        }

        otherSetting.voucherRelativeTime = voucherRelativeTime;

        var voucherList = createActivityPublicParam.otherSetting.promoTools;
        $.each(voucherList,function(i,voucher){
            if(createActivityPublicParam.isRelativeTime){
                voucher.voucherRelativeTime = voucherRelativeTime;
            }else{
               voucher.vourcherStartTime = voucherStartTime;
               voucher.voucherEndTime = voucherEndTime; 
            }
            
            voucher.voucherValidateType = voucherValidateType;
        });

        /**
         * 判断是否需要重新获取预期效果
        **/
        var oldPromoTools = createActivityPublicParam.defaultParam.promoTools;
        var newPromoTools = createActivityPublicParam.otherSetting.promoTools;
        var data = {};
        if(!ActivityUtil.compareObj(oldPromoTools,newPromoTools)){
            controller.queryExpectEffect(false);
        }else{
            data = $.extend(true,{},createActivityPublicParam.defaultParam);
        }

        data.activityStartTime = createActivityPublicParam.activityStartTime;
        data.activityEndTime = createActivityPublicParam.activityEndTime;
        data.autoDelayFlag = createActivityPublicParam.autoDelayFlag;
        // 渲染第二页
        controller.redrawSecondStepView(data);
    });

    //恢复默认设置
     $(doc).on("click", "#smCreateConsumePage .default", function() {
        //获取默认设置
        var defaultParam = createActivityPublicParam.defaultParam;

        var otherSetting = createActivityPublicParam.otherSetting;
        /**copy默认券设置
        **/
        var newPromoTools = $.extend(true,[],defaultParam.promoTools);
        otherSetting.promoTools = newPromoTools;
        otherSetting.voucherRelativeTime = defaultParam.voucherRelativeTime;


        createActivityPublicParam.activityStartTime = defaultParam.activityStartTime;
        createActivityPublicParam.activityEndTime = defaultParam.activityEndTime;
        //var controller = new ActivityCreateConsumeSmController();
        //controller.redrawFirstStepView(defaultParam);
        //恢复活动时间
        $("#smCreateConsumePage .activityStartTime").val(defaultParam.activityStartTime);
        $("#smCreateConsumePage .activityEndTime").val(defaultParam.activityEndTime);
        var controller = new ActivityCreateConsumeSmController();
        controller.redrawExpectEffectView(defaultParam);
    });
    


    /**
     * 提交活动;
     */
    $(doc).on("click","#smCreateConsumePage .submit",function(){
        if(submitFn == true){
            submitFn = false;
            function MyActivity() {
                SubmitActivityData.call(this);
            }
            MyActivity.prototype = Object.create(SubmitActivityData.prototype);
            MyActivity.prototype.checkParams = function () { 
                var actEndDate = $("#smCreateConsumePage .activityEndTime").val();
               if(actEndDate == ""){
                   DialogUtil.dialogWarn("请选择活动结束日期!");
                   return false;
               }
                              
               if(createActivityPublicParam.isRelativeTime == false){
                  if(DateUtil.compareDate(createActivityPublicParam.activityStartTime,createActivityPublicParam.voucherStartTime)){
                      DialogUtil.dialogWarn("券有效开始日期不能小于活动开始日期!");
                      return false;
                  }
                  if (DateUtil.compareDate(createActivityPublicParam.activityEndTime,createActivityPublicParam.voucherEndTime)) {
                      DialogUtil.dialogWarn("券有效结束日期不能小于活动结束日期!");
                      return false;
                  } 
                  
               }
                return true;
            };
            MyActivity.prototype.saveData = function () {
                //createNewController.saveActivityData();         
            };
            MyActivity.prototype.buildSubmitData = function () {
                this.submitData = buildActivitySubmitData(2);
            };   
            var myActivity = new MyActivity();
            myActivity.send();
            
        } 
        
    });
    //自动续期按钮点击事件
    $(doc).on("change", "#smCreateConsumePage .autoDelayFlag", function() {
        createActivityPublicParam.autoDelayFlag = $("#smCreateConsumePage .autoDelayFlag").attr("checked")?"Y":"N";
    });

    //返回按钮
    $(doc).on("click", "#smCreateConsumePage .back", function() {

        if($("#smCreateConsumePage .nextStep").length){
            //清空公共参数createActivityPublicParam
            ActivityPreloadData.clearCreateActivityParam();
            //跳转到首页
            $.router.back("index.html");
           
        }else{
            var controller = new ActivityCreateConsumeSmController();
            controller.redrawFirstStepView();

            //绑定活动日期联动控件;
            controller.bindVoucherTimeWidget();  
            //return false; 
        }
        
    });
   

    /**
     * 选择代金券有效日期类型; 一键营销没有指定时间
     */
    $(doc).on("click", "#smCreateConsumePage div[name='quan-deadline1']", function() {
        if($("#smCreateConsumePage .actions-modal-button").size()>0){
            //应该关闭模态窗口(具体怎么关由伟胜提供方法)
            $.closeModal($("#smCreateConsumePage .actions-modal"));
        }
         var _text = $(this).children("span");
         var _self = $(this);
         var buttons1 = [
             {
                 text: '相对时间',
                 onClick: function () {
                     _text.text("相对时间");
                     _self.siblings("p").hide().eq(0).show();
                     var otherSetting = createActivityPublicParam.otherSetting;
                    $("#voucherRelativeTime").val(otherSetting.voucherRelativeTime.split("|")[0]==''?'30': otherSetting.voucherRelativeTime.split("|")[0]); 

                    createActivityPublicParam.isRelativeTime = true;
                    createActivityPublicParam.autoDelayFlag = 'Y';//开启自动续期; 

                 }
             },
             {
                 text: '指定时间',
                 onClick: function () {    
                     common.confirm({
                            "title":"",
                            "content": "选择指定时间，将会关闭自动续期功能，确定要选择指定时间吗?",
                            "btnRight": "确定",
                            "btnLeft": "取消",
                             callbackLeft: function () {//取消
                                return false;
                            },
                             callbackRight: function () {//确定
                                _text.text("指定时间");
                                _self.siblings("p").hide().eq(1).show();
                                createActivityPublicParam.autoDelayFlag = 'N';//关闭自动续期;     
                                createActivityPublicParam.isRelativeTime = false; 
                                return false;
                            }
                       });           
                    
                 }
             }
         ];
         var buttons2 = [
             {
                 text: '取消',
             }
         ];
         var groups = [buttons1, buttons2];
         $.actions(groups);
    });


})(document, window);

